package db;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;

import javax.swing.JTable;
import javax.swing.table.TableColumn;

import main.app.LibraryManager;

public class TablePopulator {
	
	private Connection dbConn;
	private LibraryManager manager;
	
	private int columns;
	private Vector columnNames;
	private Vector data;
	
	private Statement stmt;
	private ResultSet rs;
	private ResultSetMetaData rsmd;

	public TablePopulator(Connection conn, LibraryManager libMan) {
		dbConn = conn;
		manager = libMan;
		columns = 0;
	}
	
	public void PopulateTable(String target) {
		try {
			stmt = dbConn.createStatement();
			if (target.equalsIgnoreCase("libro") || target.equalsIgnoreCase("autore") || target.equalsIgnoreCase("posizione_fisica"))
				rs = stmt.executeQuery("SELECT * FROM " + target);
			//TODO inserisci la query corretta per posizione_occupata
			else rs = stmt.executeQuery("SELECT * FROM " + target);
			rsmd = rs.getMetaData();
			columns = rsmd.getColumnCount();
			columnNames = new Vector(columns);
			data = new Vector();
			for (int i = 0; i < columns; i++) {
				columnNames.addElement(rsmd.getColumnName(i+1));
			}
			while (rs.next()) {
				Vector row = new Vector(columns);
				
				for (int i = 0; i < columns; i++) {
					row.addElement(rs.getObject(i+1));
				}
				data.addElement(row);
			}
			rs.close();
			stmt.close();
//			dbConn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JTable toPass = new JTable(data, columnNames);
		manager.setJTable(target, toPass);
	}
}
